package com.aglhz.nature.view;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.greenrobot.eventbus.EventBus;

import com.aglhz.base.BaseActivity;
import com.aglhz.nature.R;
import com.aglhz.nature.constants.ServerAPI;
import com.aglhz.nature.events.AroundViewEvent;
import com.aglhz.nature.modle.AroundBean;
import com.aglhz.nature.modle.BGBean;
import com.aglhz.nature.presenter.LoginPresenter;
import com.aglhz.nature.presenter.SetPresenter;
import com.aglhz.nature.utils.AsyncHttpCilentUtil;
import com.aglhz.nature.utils.Base64Coder;
import com.aglhz.nature.utils.DataCleanManager;
import com.aglhz.nature.utils.FileManager;
import com.aglhz.nature.utils.NetWorkUtil;
import com.aglhz.nature.view.iv.SetView;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.cookie.Cookie;
import cz.msebera.android.httpclient.util.TextUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SetActivity extends BaseActivity implements SetView,OnClickListener{
	private String TAG = SetActivity.this.getClass().getName();
	
	private SharedPreferences sharedPreferences; 
	private SharedPreferences NormalPreferences; 
	private ImageView changeBg;
	private ImageView clearCache;
	private ImageView feedBack;
	private ImageView aboutUs;
	private TextView logOut;
	private BGBean bgBean;
	private String data;
//	private ImageView selectimg;
	private Intent dataIntent = null;
	private String token;
	private String normalToken;
	private RelativeLayout re_changeBg ,re_clearCache,re_aboutUs;
	private SetPresenter presenter;
	private TextView cachText;
	private String url = ServerAPI.APIHEARD+ServerAPI.UPLOADBGIMAGE;//上传网络的url
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set);
		setActionBarTitle("设置");
		re_changeBg=(RelativeLayout) findViewById(R.id.re_changeBg);
		re_clearCache=(RelativeLayout) findViewById(R.id.re_clearCache);
	
		re_aboutUs=(RelativeLayout) findViewById(R.id.re_aboutUs);
		cachText=(TextView) findViewById(R.id.cachText);
		logOut=(TextView) findViewById(R.id.logOut);
		
		try {
			cachText.setText(DataCleanManager.getTotalCacheSize(getApplication()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		selectimg=(ImageView) findViewById(R.id.selectimg);
		re_changeBg.setOnClickListener(this);
		re_clearCache.setOnClickListener(this);
		re_aboutUs.setOnClickListener(this);
		logOut.setOnClickListener(this);
		sharedPreferences =getSharedPreferences("WX_INFO", Context.MODE_PRIVATE);
		token=sharedPreferences.getString("token", "");
		
		 NormalPreferences=getSharedPreferences("Normal_Info", Context.MODE_PRIVATE);
		 normalToken=NormalPreferences.getString("NORMAL_Token","");
		 presenter = new SetPresenter(this);
			// basePresenter register
					presenter.register();
	}
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.re_changeBg:
			ShowPickDialog();
			break;
		case R.id.re_clearCache:
			DataCleanManager.clearAllCache(getApplication());
			try {
				cachText.setText(DataCleanManager.getTotalCacheSize(getApplication()));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.re_aboutUs:
			Intent intent =new Intent(SetActivity.this,AboutUsActivity.class);
			startActivity(intent);
			break;
		case R.id.logOut:
			presenter.logOut();
			break;

		default:
			break;
		}
		
	}
	
	/**
	 * 选择提示对话框
	 */
	private void ShowPickDialog() {
		new AlertDialog.Builder(this)
				.setTitle("选择图片")
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					
						Intent intent = new Intent(Intent.ACTION_PICK, null);
						
						/**
						 * 下面这句话，与其它方式写是一样的效果，如果：
						 * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						 * intent.setType(""image/*");设置数据类型
						 * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
						 * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
						 */
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/*");
						startActivityForResult(intent, 1);

					}
				})
				.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						/**
						 * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
						 
						 */
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						//下面这句指定调用相机拍照后的照片存储的路径
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								.fromFile(new File(Environment
										.getExternalStorageDirectory(),
										"xiaoma.jpg")));
						startActivityForResult(intent, 2);
					}
				}).show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		// 如果是直接从相册获取
		case 1:
			startPhotoZoom(data.getData());
			break;
		// 如果是调用相机拍照时
		case 2:
			File temp = new File(Environment.getExternalStorageDirectory()
					+ "/xiaoma.jpg");
			startPhotoZoom(Uri.fromFile(temp));
			break;
		// 取得裁剪后的图片
		case 3:
			/**
			 * 非空判断大家一定要验证，如果不验证的话，
			 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
			 * 当前功能时，会报NullException，小马只
			 * 在这个地方加下，大家可以根据不同情况在合适的
			 * 地方做判断处理类似情况
			 * 
			 */
			if(data != null){
				dataIntent = data;
				setPicToView(data);
				try {
					uploadPic(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +"Picture.png");
				} catch (Exception e) {
				Log.e("cuowu","出错了--------");
				}
				
			}
			break;
		default:
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	
	
	/**
	 * 裁剪图片方法实现
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		/*
		 * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
		 * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
		 * 制做的了...吼吼
		 */
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		//下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 2);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);		
		Log.i("tag", "yao裁剪图片...");
	}
	/**
	 * 保存裁剪之后的图片数据
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
//			Drawable drawable = new BitmapDrawable(photo);
			Log.i("tag", "保存图片：正在打开文件...");
			try
			{
			FileOutputStream fileOutputStream = new FileOutputStream(new File( Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +"Picture.png"));
			Log.e("tag", Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +"Picture.png");
			ByteArrayOutputStream baops = new ByteArrayOutputStream();

			photo.compress(CompressFormat.PNG, 100, baops);

			Log.i("tag", "保存图片：正在保存数据...");

			fileOutputStream.write(baops.toByteArray());

			Log.i("tag", "保存图片：正在关闭输出流...");

			fileOutputStream.close();
		}
		catch (Exception e)
		{
			Log.e("tag", "保存图片：异常（" + e.getMessage() + "）");
			e.printStackTrace();			
		}

		Log.i("tag", "保存图片：保存成功");
		
		}
	}
	
	//上传
	private void uploadPic(String path) throws Exception{
		File file = new File(path);  
		Log.e("---1--","------1------");
		if (file.exists() && file.length() > 0) {  
			AsyncHttpClient client =  AsyncHttpCilentUtil.getInstance(SetActivity.this);
		    RequestParams params = new RequestParams();  
		    params.put("file", file);  
		    Log.e("---2--","------2------");
		    getCookieText();
		 client.post(url, params, new TextHttpResponseHandler(){
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				Log.e("---3--","------3------"+responseString+statusCode);
				 Log.e("URL",url);
				getCookieText();
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String responseString) {
				// TODO Auto-generated method stub
				Log.e("---4--","------4------");
				 try {
					 Log.e("BG返回信息", "response" + responseString);
					
					 Gson gson = new Gson();
					
					BGBean cBean = gson.fromJson(responseString,
							BGBean.class);
					 bgBean= (BGBean) cBean.clone();
					
					Log.d("BG返回信息"," bgBean---111-----"+bgBean.getOther());	
					data = bgBean.getData();
					Log.d("BG返回信息"," bgBean---mcp-----"+ bgBean.getData());
					int code = Integer.parseInt(bgBean.getOther().getCode());
					 if(200==code){
						 Toast.makeText(SetActivity.this, "上传成功", Toast.LENGTH_LONG).show();
					 }
					 
					 Log.e("BG返回信息", "success" + "success");
					 } catch (Exception e) {
					 e.printStackTrace();
					 }
				
			}

			
			 
		 });
		} else {  
		    Toast.makeText(SetActivity.this, "文件不存在", Toast.LENGTH_LONG).show();  
		} 
		 
		// Upload a File
//		if(dataIntent != null){
//			Bundle extras = dataIntent.getExtras();
//			if (extras != null) {
//				Bitmap photo = extras.getParcelable("data");
//				Drawable drawable = new BitmapDrawable(photo);
//				
//				/**
//				 * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上
//				 * 传到服务器，QQ头像上传采用的方法跟这个类似
//				 */
//				
//				ByteArrayOutputStream stream = new ByteArrayOutputStream();
//				photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
//				byte[] bytes = stream.toByteArray();
//				// 将图片流以字符串形式存储下来
//				
//				final String picStr = new String(Base64Coder.encodeLines(bytes));
//				
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						List<NameValuePair> params = new ArrayList<NameValuePair>();
//						params.add(new BasicNameValuePair("picStr", picStr));
//						params.add(new BasicNameValuePair("picName", "dengzi"));
//						final String result = NetWorkUtil.httpPost(url,params);
//						runOnUiThread(new Runnable() {
//							public void run() {
//								Toast.makeText(SetActivity.this, result, Toast.LENGTH_SHORT).show();
//								Log.e(" result", result);
//							}
//						});
//					}
//				}).start();
//				
//				//如果下载到的服务器的数据还是以Base64Coder的形式的话，可以用以下方式转换
//				//为我们可以用的图片类型就OK啦...吼吼
//				//Bitmap dBitmap = BitmapFactory.decodeFile(tp);
//				//Drawable drawable = new BitmapDrawable(dBitmap);
//				
//			}
//		}else {
//			Toast.makeText(SetActivity.this, "图片不存在", Toast.LENGTH_SHORT).show();
//		}
	}
	@Override
	public void changeToLogIn() {
		Intent intent=new Intent(SetActivity.this,LoginActivity.class);
		startActivity(intent);
		
	}
	
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		presenter.unregister();
	}
	
	
	@Override
	public void ClearUserInfo() {
		if(!(""==token)){
			sharedPreferences = SetActivity.this.getSharedPreferences("WX_INFO", Context.MODE_PRIVATE);
			sharedPreferences.edit().clear().commit(); 
		}else if(!(""==normalToken)){
			
			 NormalPreferences=getSharedPreferences("Normal_Info", Context.MODE_PRIVATE);
			 NormalPreferences.edit().clear().commit(); 
			 Log.e("普通注销","----------success-------");
		}
		
	}
	private String getPrivateRoot()
	{
		return SetActivity.this.getFilesDir().getAbsolutePath() + File.separator;
	}
	
	 /** 
     * 获取标准 Cookie   
     */  
    private String getCookieText() {  
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this.getApplicationContext());  
        List<Cookie> cookies = myCookieStore.getCookies();  
        Log.d(TAG, "Se cookies.size() = " + cookies.size());  
       
        for (Cookie cookie : cookies) {  
            Log.d(TAG, cookie.getName() + " set= " + cookie.getValue());  
        }  
         StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < cookies.size(); i++) {  
             Cookie cookie = cookies.get(i);  
             String cookieName = cookie.getName();  
             String cookieValue = cookie.getValue();  
            if (!TextUtils.isEmpty(cookieName)  
                    && !TextUtils.isEmpty(cookieValue)) {  
                sb.append(cookieName + " set=");  
                sb.append(cookieValue + ";");  
            }  
        }  
        Log.e("cookie setActivity", sb.toString());  
        return sb.toString();  
    }  
}
